package ofpof.web.controller;

import ofpof.domain.CaptchaToken;
import ofpof.service.CaptchaService;
import ofpof.service.SecurityService;
import ofpof.web.form.PasswordReminderForm;
import ofpof.web.validator.PasswordReminderFormValidator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ForgotPasswordController {
	
	@Autowired
	private CaptchaService captchaService;

	@Autowired
	private PasswordReminderFormValidator passwordReminderFormValidator;
	
	@Autowired
	private SecurityService securityService;
	
	@RequestMapping(value = "/password/remind", method = RequestMethod.GET)
	public ModelAndView showPasswordReset() {
		ModelAndView mav = new ModelAndView("passwordremind");
		CaptchaToken captchaToken = captchaService.createNewCaptcha();
		PasswordReminderForm passwordReminderForm = new PasswordReminderForm();
		passwordReminderForm.setCaptchaId(captchaToken.getId().toString());
		mav.addObject("passwordform",passwordReminderForm);
		return mav;
	}
	
	@RequestMapping(value="/password/remind", method= RequestMethod.POST)
	public String  doPasswordReset(@ModelAttribute("passwordform") PasswordReminderForm passwordReminderForm,BindingResult bindingResult ) {
		
		passwordReminderFormValidator.validate(passwordReminderForm, bindingResult);
		
		if (bindingResult.hasErrors()) {
			passwordReminderForm.setCaptcha(null);
			
			return "passwordform";
		}
		
		captchaService.removeCaptcha(passwordReminderForm.getCaptchaId());
		securityService.sendUserEmail(passwordReminderForm.getEmail());
		return "redirect:../password/sent";
	}
	
	@RequestMapping(value = "/password/sent", method = RequestMethod.GET)
	public String passwordSent() {
		return "passwordSent";
	}


}
